import React, { useState, useEffect, useRef, useCallback } from 'react';
import styles from './HomePage.module.css';
import { isMobileDevice } from '../../utils/platform';

// 配置常量
const ANIMATION_DURATION = 600;
const ANIMATION_EASING = 'cubic-bezier(0.25, 0.46, 0.45, 0.94)';
const PARTICLE_COUNT = 80;

// 页面sections配置
const SECTIONS = [
  {
    id: 'hero',
    title: 'Lingverse',
    subtitle: '新一代智能数据平台',
    description: '融合前沿AI技术与云端架构，打造企业级数据分析与智能决策平台',
    icon: 'platform',
    gradient: 'from-blue-600 via-purple-600 to-indigo-800'
  },
  {
    id: 'analytics',
    title: '数据分析引擎',
    subtitle: '深度洞察 · 智能决策',
    description: '多维度数据建模、实时分析处理、可视化报表生成，让数据驱动业务增长',
    icon: 'analytics',
    gradient: 'from-purple-600 via-pink-600 to-red-600'
  },
  {
    id: 'ai-engine',
    title: 'AI智能引擎',
    subtitle: '灵小犀 - 智能数据助手',
    description: '机器学习算法、自然语言处理、智能预测分析，为企业提供AI驱动的数据洞察',
    icon: 'ai-brain',
    gradient: 'from-green-600 via-teal-600 to-blue-600'
  },
  {
    id: 'cloud-infrastructure',
    title: '云端基础架构',
    subtitle: '弹性扩展 · 安全可靠',
    description: '分布式云架构、弹性计算资源、企业级安全保障，构建稳定高效的数据处理环境',
    icon: 'cloud',
    gradient: 'from-orange-600 via-red-600 to-pink-600'
  }
];

// 图标组件
const getIcon = (iconType: string) => {
  const iconProps = {
    fill: "none",
    stroke: "currentColor",
    viewBox: "0 0 24 24",
    strokeWidth: 2
  };

  switch (iconType) {
    case "platform":
      return (
        <svg {...iconProps}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 14.25h13.5m-13.5 0a3 3 0 01-3-3m3 3a3 3 0 100 6h13.5a3 3 0 100-6m-16.5-3a3 3 0 013-3h13.5a3 3 0 013 3m-19.5 0a4.5 4.5 0 01.9-2.7L5.737 5.1a3.375 3.375 0 012.7-1.35h7.126c1.062 0 2.062.5 2.7 1.35l2.587 3.45a4.5 4.5 0 01.9 2.7m0 0a3 3 0 01-3 3m0 3h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008zm-3 6h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008z" />
        </svg>
      );
    case "analytics":
      return (
        <svg {...iconProps}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
        </svg>
      );
    case "ai-brain":
      return (
        <svg {...iconProps}>
          <rect x="4" y="4" width="16" height="16" rx="2" ry="2" strokeLinecap="round" strokeLinejoin="round" />
          <rect x="9" y="9" width="6" height="6" rx="1" ry="1" strokeLinecap="round" strokeLinejoin="round" />
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3" />
          <circle cx="12" cy="12" r="1" fill="currentColor" />
          <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v1M12 14v1M9 12h1M14 12h1" />
        </svg>
      );
    case "cloud":
      return (
        <svg {...iconProps}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 15a4.5 4.5 0 004.5 4.5H18a3.75 3.75 0 001.332-7.257 3 3 0 00-3.758-3.848 5.25 5.25 0 00-10.233 2.33A4.502 4.502 0 002.25 15z" />
        </svg>
      );
    default:
      return null;
  }
};

const HomePage: React.FC = () => {
  const [activeSection, setActiveSection] = useState(0);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [isLoaded, setIsLoaded] = useState(false);
  const [isScrolling, setIsScrolling] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const lastScrollTime = useRef<number>(0);
  const scrollAccumulator = useRef<number>(0);
  const lastScrollDirection = useRef<number>(0);
  const touchStartY = useRef<number>(0);
  const touchStartTime = useRef<number>(0);



  // 生成动态粒子（移动端优化）
  const generateParticles = () => {
    const particles = [];
    const isMobile = isMobileDevice();
    const particleCount = isMobile ? 20 : PARTICLE_COUNT; // 移动端减少到20个粒子
    
    for (let i = 0; i < particleCount; i++) {
      particles.push({
        id: i,
        x: Math.random() * 100,
        y: Math.random() * 100,
        size: Math.random() * 4 + 1,
        speed: Math.random() * 2 + 0.5,
        delay: Math.random() * 5
      });
    }
    return particles;
  };

  const particles = generateParticles();

  // 鼠标移动追踪
  const handleMouseMove = useCallback((e: MouseEvent) => {
    setMousePosition({
      x: (e.clientX / window.innerWidth) * 100,
      y: (e.clientY / window.innerHeight) * 100
    });
  }, []);

  // 切换到指定section（优化版本）
  const scrollToSection = useCallback((sectionIndex: number) => {
    if (sectionIndex === activeSection || !containerRef.current || isScrolling) return;

    setIsScrolling(true);
    setActiveSection(sectionIndex);
    
    const targetY = -sectionIndex * window.innerHeight;
    const container = containerRef.current;
    
    // 移动端使用更快的动画
    const isMobile = isMobileDevice();
    const duration = isMobile ? 400 : ANIMATION_DURATION;
    const easing = isMobile ? 'cubic-bezier(0.25, 0.8, 0.25, 1)' : ANIMATION_EASING;
    
    // 使用GPU加速的transform3d
    container.style.transition = `transform ${duration}ms ${easing}`;
    container.style.transform = `translate3d(0, ${targetY}px, 0)`;
    
    setTimeout(() => {
      if (container) {
        container.style.transition = '';
      }
      setIsScrolling(false);
    }, duration);
  }, [activeSection, isScrolling]);

  // 滚轮事件处理（带节流和灵敏度控制）
  const handleWheel = useCallback((e: WheelEvent) => {
    e.preventDefault();
    
    // 如果正在滚动动画中，忽略滚轮事件
    if (isScrolling) return;
    
    const now = Date.now();
    const timeSinceLastScroll = now - lastScrollTime.current;
    
    // 检测是否是触摸板（deltaY较小且频繁）
    const isTouchpad = Math.abs(e.deltaY) < 120;
    const minInterval = isTouchpad ? 300 : 200;
    const scrollThreshold = isTouchpad ? 80 : 30;
    
    // 节流控制：根据设备类型调整间隔
    if (timeSinceLastScroll < minInterval) return;
    
    // 获取当前滚动方向 (1: 向下, -1: 向上)
    const currentDirection = e.deltaY > 0 ? 1 : -1;
    
    // 如果方向改变，重置累积器
    if (lastScrollDirection.current !== 0 && lastScrollDirection.current !== currentDirection) {
      scrollAccumulator.current = 0;
    }
    
    // 更新方向记录
    lastScrollDirection.current = currentDirection;
    
    // 累积滚动距离
    scrollAccumulator.current += Math.abs(e.deltaY);
    
    // 达到阈值时执行切换
    if (scrollAccumulator.current >= scrollThreshold) {
      if (currentDirection > 0 && activeSection < SECTIONS.length - 1) {
        // 向下滚动，切换到下一个section
        scrollToSection(activeSection + 1);
        lastScrollTime.current = now;
        scrollAccumulator.current = 0;
        lastScrollDirection.current = 0;
      } else if (currentDirection < 0 && activeSection > 0) {
        // 向上滚动，切换到上一个section
        scrollToSection(activeSection - 1);
        lastScrollTime.current = now;
        scrollAccumulator.current = 0;
        lastScrollDirection.current = 0;
      }
    }
  }, [activeSection, SECTIONS.length, scrollToSection, isScrolling]);

  // 触摸开始事件处理
  const handleTouchStart = useCallback((e: TouchEvent) => {
    if (isScrolling) return;
    
    touchStartY.current = e.touches[0].clientY;
    touchStartTime.current = Date.now();
  }, [isScrolling]);

  // 触摸结束事件处理
  const handleTouchEnd = useCallback((e: TouchEvent) => {
    if (isScrolling) return;
    
    const touchEndY = e.changedTouches[0].clientY;
    const touchEndTime = Date.now();
    const deltaY = touchStartY.current - touchEndY;
    const deltaTime = touchEndTime - touchStartTime.current;
    
    // 最小滑动距离和时间（保持原有参数）
    const minSwipeDistance = 50;
    const maxSwipeTime = 300;
    
    // 检查是否为有效滑动
    if (Math.abs(deltaY) < minSwipeDistance || deltaTime > maxSwipeTime) {
      return;
    }
    
    const now = Date.now();
    const timeSinceLastScroll = now - lastScrollTime.current;
    
    // 防止过快连续滑动（保持原有参数）
    if (timeSinceLastScroll < 500) return;
    
    // 根据滑动方向切换section
    if (deltaY > 0 && activeSection < SECTIONS.length - 1) {
      // 向上滑动，切换到下一个section
      scrollToSection(activeSection + 1);
      lastScrollTime.current = now;
    } else if (deltaY < 0 && activeSection > 0) {
      // 向下滑动，切换到上一个section
      scrollToSection(activeSection - 1);
      lastScrollTime.current = now;
    }
  }, [activeSection, SECTIONS.length, scrollToSection, isScrolling]);

  // 键盘事件处理
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    // 如果正在滚动动画中，忽略键盘事件
    if (isScrolling) return;
    
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        if (activeSection < SECTIONS.length - 1) scrollToSection(activeSection + 1);
        break;
      case 'ArrowUp':
        e.preventDefault();
        if (activeSection > 0) scrollToSection(activeSection - 1);
        break;
    }
  }, [activeSection, SECTIONS.length, scrollToSection, isScrolling]);

  // 初始化效果
  useEffect(() => {
    setIsLoaded(true);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('keydown', handleKeyDown);
    
    const container = containerRef.current;
    if (container) {
      // 添加滚轮事件（桌面端）
      container.addEventListener('wheel', handleWheel, { passive: false });
      
      // 添加触摸事件（移动端）
      if (isMobileDevice()) {
        container.addEventListener('touchstart', handleTouchStart, { passive: true });
        container.addEventListener('touchend', handleTouchEnd, { passive: true });
      }
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('keydown', handleKeyDown);
      if (container) {
        container.removeEventListener('wheel', handleWheel);
        if (isMobileDevice()) {
          container.removeEventListener('touchstart', handleTouchStart);
          container.removeEventListener('touchend', handleTouchEnd);
        }
      }
    };
  }, [handleMouseMove, handleKeyDown, handleWheel, handleTouchStart, handleTouchEnd]);



  return (
    <div className={`${styles.container} ${isLoaded ? styles.loaded : ''}`}>
      {/* 动态背景粒子 */}
      <div className={styles.particleField}>
        {particles.map(particle => (
          <div
            key={particle.id}
            className={styles.particle}
            style={{
              left: `${particle.x}%`,
              top: `${particle.y}%`,
              width: `${particle.size}px`,
              height: `${particle.size}px`,
              animationDelay: `${particle.delay}s`,
              animationDuration: `${particle.speed + 3}s`
            }}
          />
        ))}
      </div>

      {/* 鼠标跟随光效 */}
      <div 
        className={styles.mouseGlow}
        style={{
          left: `${mousePosition.x}%`,
          top: `${mousePosition.y}%`
        }}
      />

      {/* 主内容区域 */}
      <div className={styles.mainContent} ref={containerRef}>
        {SECTIONS.map((section, index) => (
          <section 
            key={section.id} 
            className={`${styles.section} ${index === activeSection ? styles.active : ''}`}
            data-section={section.id}
          >
            <div className={styles.sectionContent}>
              {/* 左侧内容 */}
              <div className={styles.contentLeft}>
                <div className={styles.sectionNumber}>
                  {String(index + 1).padStart(2, '0')}
                </div>
                <h1 className={styles.sectionTitle}>
                  <span className={styles.titleNumber}>
                    {String(index + 1).padStart(2, '0')}
                  </span>
                  <span className={styles.titleText}>{section.title}</span>
                </h1>
                <h2 className={styles.sectionSubtitle}>{section.subtitle}</h2>
                <p className={styles.sectionDescription}>{section.description}</p>
                
                {/* 交互按钮组 */}
                <div className={styles.actionButtons}>
                  <button className={styles.primaryButton}>
                    <span>探索更多</span>
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                    </svg>
                  </button>
                  <button className={styles.secondaryButton}>
                    了解详情
                  </button>
                </div>
              </div>

              {/* 右侧视觉元素 */}
              <div className={styles.contentRight}>
                <div className={styles.visualCard}>
                  <div className={styles.cardIcon}>
                    {getIcon(section.icon)}
                  </div>
                  <div className={styles.cardGlow}></div>
                  <div className={styles.cardGrid}></div>
                </div>
              </div>
            </div>

            {/* 装饰性数据流 */}
            <div className={styles.dataFlow}>
              {Array.from({ length: 5 }, (_, i) => (
                <div key={i} className={styles.flowLine} style={{ animationDelay: `${i * 0.5}s` }} />
              ))}
            </div>
          </section>
        ))}
      </div>

      {/* 侧边导航 */}
      <nav className={styles.sideNavigation}>
        {SECTIONS.map((section, index) => (
          <button
            key={section.id}
            className={`${styles.navDot} ${index === activeSection ? styles.active : ''}`}
            onClick={() => scrollToSection(index)}
            title={section.title}
          >
            <span className={styles.navLabel}>{section.title}</span>
          </button>
        ))}
      </nav>

      {/* 底部进度条 */}
      <div className={styles.progressBar}>
        <div 
          className={styles.progressFill}
          style={{ width: `${((activeSection + 1) / SECTIONS.length) * 100}%` }}
        />
      </div>
    </div>
  );
};

export default HomePage;
